package com.enqualcomm.kids.network;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.enqualcomm.kids.network.socket.request.BasicParams;
import com.enqualcomm.kids.network.socket.response.BasicResult;

import common.utils.GsonFactory;
import common.utils.MyLogger;

public class SocketRequest<T extends BasicResult> extends Request<T> {

    private NetworkListener<T> mListener;
    private final BasicParams params;

    public SocketRequest(BasicParams p,NetworkListener<T> listener){
        super(Method.GET, "", null);
        mListener = listener;
        params = p;
        setShouldCache(false);//不需要缓存
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
//        MyApplication.lastPingDate = SystemClock.elapsedRealtime();//记录连接服务器的时间
        String json = GsonFactory.newInstance().toJson(params);
        MyLogger.jLog().i(json);
        return json.getBytes();
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        String json = new String(response.data);
        MyLogger.jLog().i(json);

        if (mListener!=null){
            T t = GsonFactory.newInstance().fromJson(json, params.getResponsePojo());
            return Response.success(t, null);
        }else{//有时不需要关心结果，只要发送而已，不需要解析
            return Response.error(new VolleyError("没有注册Listener"));
        }
    }

    @Override
    protected void deliverResponse(T response) {
        if (mListener!=null){
            mListener.onSuccess(response);
        }
    }

    @Override
    public void deliverError(VolleyError error) {
        if (mListener!=null) {
            mListener.onError(error);
        }
    }

    @Override
    protected void onFinish() {
        super.onFinish();
        mListener = null;
    }
}